import {Form, FormField, Label, LinkButton, NumberBox, RadioButton, TextBox} from "rc-easyui";
import React, {useEffect, useRef, useState} from "react";
import {tfield, tparam, tt} from "@kordar-lib/i18n";
import {FormDataType} from "@kordar-lib/base";
import {$toast} from "@kordar/easyui";
import {convertToText, fetchConfigOptions, resourceService} from "@kordar/easyui-tpl";
import {fetchConfigOptionsWithList} from "../../util/helper";
import ReactJson from "react-json-view";

const FormPanel = ({ctx, type, record, pageConfig, fetchConfig, close, refs}) => {

    const [formData, loadFormData] = useState(record)
    const form = useRef(null)

    const [jsonData, setJsonData] = useState(JSON.parse(formData.config||"{}"));

    const rules = {
        name: {required: true},
    }

    const handleChange = (name, value) => {
        if (name === "driver") {
            checkDataJson(value);
        }
        loadFormData({...formData, [name]: value})
    };

    const checkDataJson = (value) => {
      if (value === "local") {
          setJsonData(Object.assign({"root": ""}, jsonData));
      }
      if (value === "cos") {
          setJsonData(Object.assign({"bucketName": "", "region": "", "secretId": "", "secretKey": ""}, jsonData));
      }
    }

    useEffect(() => {
        ctx.setMethod("submitForm", onSubmit)
    }, [])

    // 提交数据
    const onSubmit = () => {

        form.current.validate((errors) => {
            if (errors != null) {
                $toast.error(convertToText(errors));
                return
            }

            let data = {
                id: parseInt(formData.id),
                name: formData.name,
                driver: formData.driver,
                config: JSON.stringify(jsonData),
                remark: formData.remark,
            }
            let formBody = {object: data, conditions: []}
            if (type === FormDataType.UPDATE) {
                formBody.conditions.push({key: "id", value: record.id})
            }
            resourceService.saveResult(ctx?.name(), type, formBody, () => {
                $toast.success(tt("save_success", "Message"))
                ctx.refresh()
                close()
            }).then(r => {});
        })

    }

    const handleEdit = (edit) => {
        if (edit.updated_src) {
            setJsonData(edit.updated_src)
        }
    };

    return (
        <Form ref={form}
              model={formData}
              labelWidth={120}
              labelAlign="left"
              errorType="tooltip"
              rules={rules}
              style={{minWidth: 500, padding: '20px'}}
              onChange={handleChange}
        >

            <FormField name="name" label={tfield(pageConfig, 'name.label', 'Name') + ":"}>
                <TextBox placeholder={tfield(pageConfig, 'name.placeholder', '')} value={formData.name}></TextBox>
            </FormField>
            <FormField name="remark" label={tfield(pageConfig, 'remark.label', 'Remark') + ":"}>
                <TextBox multiline style={{height: 120, padding: '5px 0'}} placeholder={tfield(pageConfig, 'remark.placeholder', '')} value={formData.remark}></TextBox>
            </FormField>
            <FormField name="driver" label={tfield(pageConfig, 'driver.label', 'Driver') + ":"}>
                <div>
                    {fetchConfigOptionsWithList(fetchConfig, "driver", pageConfig).map(item => {
                        return <span key={item.value}>
                            <RadioButton value={item.value}
                                         groupValue={formData.driver + ''}
                                         inputId={'driver-' + item.value}
                            >
                            </RadioButton>
                            <Label htmlFor={'driver-' + item.value}
                                   style={{margin: '0 5px', width: 'auto'}}>{item.text}</Label>
                        </span>
                    })}
                </div>
            </FormField>
            <FormField name="config" label={tfield(pageConfig, 'config.label', 'Config') + ":"}>
                <div>
                    <ReactJson
                        src={jsonData}
                        onEdit={handleEdit}
                        onAdd={handleEdit}
                        onDelete={handleEdit}
                        collapsed={false}
                        enableClipboard={true}
                        displayDataTypes={false}
                    />
                </div>
            </FormField>

            <div className="admin-form-submit">
                <LinkButton style={{width: 80}} onClick={onSubmit} iconCls="icon-save">{tparam(pageConfig, 'submit.text', 'Submit')}</LinkButton>
                <LinkButton style={{width: 80}} onClick={close} iconCls="icon-cancel">{tparam(pageConfig, 'close.text', 'Close')}</LinkButton>
            </div>
        </Form>
    )

}

export default FormPanel
